Roman to Integer

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

题目大意:将一个1-3999范围内的罗马数字转为整数

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/8
 * I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)
 * 左>右,左+右; 左<右,右-左
 * MCMXCVI => 1000 + 100 + 1000 + 10 + 100 - 20 + 5 + 1
 */
public class Solution {
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) return 0;
        int[] valueMap = new int[26];

        valueMap['I' - 'A'] = 1;
        valueMap['V' - 'A'] = 5;
        valueMap['X' - 'A'] = 10;
        valueMap['L' - 'A'] = 50;
        valueMap['C' - 'A'] = 100;
        valueMap['D' - 'A'] = 500;
        valueMap['M' - 'A'] = 1000;

        int len = s.length();
        int last = s.charAt(0) - 'A';
        int result = valueMap[last];
        for (int i = 1; i < len; i++) {
            int ch = s.charAt(i) - 'A';
            result += valueMap[ch];
            if (valueMap[ch] > valueMap[last]) {
                result -= valueMap[last] * 2;
            }
            last = ch;
        }
        return result;
    }
}

参考:维基百科——罗马数字

gzdaijie            updated 2016-05-08 17:03:02

results matching ""

    No results matching ""